package com.coco.admin.service.impl;

import com.coco.admin.mapper.SysUserLoginMapper;
import com.coco.admin.pojo.TbAdmin;
import com.coco.admin.service.SysUserLoginService;
import com.coco.admin.vo.LoginAdminVo;
import com.coco.common.constant.LoginEnum;
import com.coco.common.result.CommonResponse;
import com.coco.common.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author minicoco
 * @version 1.0
 * @date 2021/7/23 11:25
 */
@Service
public class SysUserLoginServiceImpl implements SysUserLoginService {

    @Autowired(required = false)
    private SysUserLoginMapper userLoginMapper;
    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public CommonResponse adminLogin(LoginAdminVo adminVo) {
        //判断用户名或密码是否为空
        if (!StringUtils.isEmpty(adminVo.getPhone()) && !StringUtils.isEmpty(adminVo.getPassword())){
            //通过手机号查询用户信息
            TbAdmin admin = userLoginMapper.findUserByPhone(adminVo.getPhone());
            //判断用户是否登陆成功
            if (admin!=null && adminVo.getPassword().equals(admin.getPassword())){
                Map<String, String> token = tokenUtil.getToken(admin.getPhone(), adminVo.getType());
                return new CommonResponse(LoginEnum.LOGIN_SUCCESS.getCode(),LoginEnum.LOGIN_SUCCESS.getMessage(),token);
            }
            return new CommonResponse(LoginEnum.LOGIN_FAIL.getCode(),LoginEnum.LOGIN_FAIL.getMessage());
        }
        return new CommonResponse(LoginEnum.LOGIN_MSG_ERROR.getCode(), LoginEnum.LOGIN_MSG_ERROR.getMessage());
    }

    @Override
    public TbAdmin findLoginUser(String token) {
        String phone = redisTemplate.boundValueOps(token).get();
        if (phone!=null){
            TbAdmin userByPhone = userLoginMapper.findUserByPhone(phone);
            userByPhone.setPassword("");
            return userByPhone;
        }
        return null;
    }

    @Override
    public CommonResponse logout(String token, String type) {
        //从redis 中获取用户手机号
        String phone = redisTemplate.boundValueOps(token).get();
        //删除redis中的token信息
        boolean b = tokenUtil.removeToken(phone, type);
        if (b){
            //删除redis中的用户信息
            redisTemplate.delete(token);
            return new CommonResponse(LoginEnum.LOGOUT_SUCCESS.getCode(),LoginEnum.LOGOUT_SUCCESS.getMessage());
        }
        return null;
    }
}
